<template>
  <div class="forget-password-box">
    <div v-if="!isSendSuccess" class="icon-box">
      <svg-icon icon-name="icon-guanbi" color="red" size="100px"></svg-icon>
    </div>
    <div v-else class="icon-box success-box">
      <svg-icon icon-name="icon-icon" color="#00c091" size="100px"></svg-icon>
      <p>密码重置成功!</p>
    </div>
    <!-- 邮箱填写 -->
    <div class="email-box">
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="160px"
        class="demo-ruleForm"
        status-icon
        size="normal"
        label-position="top"
      >
        <el-form-item label="请填写您的手机号码" prop="phone" placeholder="请输入手机号">
          <el-input v-model="ruleForm.phone" type="phone" />
        </el-form-item>

        <el-form-item prop="verifyCode">
          <el-row :gutter="15">
            <el-col :span="16">
              <el-input v-model="ruleForm.verifyCode" placeholder="请输入验证码">
                <el-button slot="append" icon="el-icon-search"></el-button>
              </el-input>
            </el-col>
            <el-col :span="8">
              <el-link type="primary" :disabled="!showCaptcha" @click="sendVerifyCode">
                {{ captchaBottomName }}
                <span v-show="!showCaptcha">({{ countCaptcha }}s)</span>
              </el-link>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="新密码:" prop="newPassword">
          <el-input v-model="ruleForm.newPassword" type="password" />
        </el-form-item>
        <el-form-item label="确认密码:" prop="confirmPassword">
          <el-input v-model="ruleForm.confirmPassword" type="password" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="isLoading" @click="submitForm(ruleFormRef)"
            >重置密码
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script lang="ts" setup>
  import { forgetPasswordAsync, sendSmsVerifyCode } from '@/http/api/user';
  import { ElMessage, FormInstance, FormRules } from 'element-plus';

  const isSendSuccess = ref<boolean>(false);
  const isLoading = ref<boolean>(false);

  const ruleForm = reactive({
    phone: '',
    verifyCode: '',
    newPassword: '',
    confirmPassword: ''
  });
  const ruleFormRef = ref<FormInstance>();
  // 密码校验规则
  const passwordValidator = (rule: any, value: string, callback: Function) => {
    let pwdRegex = new RegExp('(?=.*[0-9])(?=.*[a-zA-Z]).{8,30}');
    if (!value) {
      callback(new Error('新密码不能为空'));
    } else if (!pwdRegex.test(value)) {
      callback(new Error('密码中必须包含字母、数字,至少8个字符'));
    } else {
      callback();
    }
  };
  // 确认密码的自定义规则
  const surePassValidator = (rule: any, value: string, callback: Function) => {
    if (!value) {
      callback(new Error('请再次确认密码'));
    } else if (ruleForm.newPassword !== value) {
      callback(new Error('两次输入密码不一致'));
    } else {
      callback();
    }
  };
  const rules = reactive<FormRules>({
    verifyCode: [{ required: true, message: '验证码不能为空', trigger: 'change' }],
    phone: [
      { required: true, message: '请输入手机号', trigger: 'blur' },
      { pattern: /^1[3456789]\d{9}$/, message: '目前只支持中国大陆的手机号码' }
    ],
    newPassword: [
      { required: true, message: '请输入新密码', trigger: 'blur' },
      {
        required: true,
        validator: passwordValidator,
        trigger: 'change'
      }
    ],
    confirmPassword: [{ required: true, validator: surePassValidator, trigger: 'change' }]
  });
  const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate(async (valid, fields) => {
      if (valid) {
        let params = {
          phone: ruleForm.phone,
          verifyCode: ruleForm.verifyCode,
          confirmPassword: ruleForm.confirmPassword,
          newPassword: ruleForm.newPassword
        };
        isLoading.value = true;
        const data = await forgetPasswordAsync(params);
        if (data.code === 200) {
          isSendSuccess.value = true;
          ElMessage({
            message: '重置成功',
            type: 'success'
          });
          isLoading.value = false;
        } else {
          isSendSuccess.value = false;
          isLoading.value = false;
          ElMessage({
            message: data.msg,
            type: 'error'
          });
        }
      } else {
        console.log('error submit!', fields);
      }
    });
  };

  const showCaptcha = ref<boolean>(true); // 初始启用按钮
  const countCaptcha = ref<number>(60);
  const captchaBottomName = ref<string>('获取验证码');
  let timer = 0;
  const sendVerifyCode = async () => {
    sendSmsVerifyCode(ruleForm.phone).then((result: { code: number; msg: any }) => {
      if (result.code === 200) {
        if (!timer) {
          showCaptcha.value = false;
          countCaptcha.value = 60;
          captchaBottomName.value = '重新获取';
          timer = setInterval(() => {
            if (countCaptcha.value > 0 && countCaptcha.value <= 60) {
              countCaptcha.value--;
            } else {
              showCaptcha.value = true;
              clearInterval(timer); // 清除定时器
              timer = 0;
            }
          }, 1000);
        }
        ElMessage({
          message: '发送成功',
          type: 'success'
        });
      } else {
        ElMessage({
          message: result.msg,
          type: 'error'
        });
      }
    });
  };
</script>
<style lang="scss" scoped>
  .forget-password-box {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    padding-top: 30px;

    .success-box {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      color: #00c091;

      p {
        margin-top: 15px;
      }
    }

    .email-box {
      margin-top: 30px;
    }
  }
</style>
